package com.sj.controller;

import cn.hutool.core.bean.BeanUtil;
import com.sj.common.bean.LocalUser;
import com.sj.common.dto.praise.PraiseParam;
import com.sj.common.exception.CustomException;
import com.sj.common.lang.ApiResult;
import com.sj.common.lang.Const;
import com.sj.common.lang.RedisConst;
import com.sj.entity.Praise;
import com.sj.entity.User;
import com.sj.interceptor.AuthCheck;
import com.sj.service.PraiseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 点赞表 前端控制器
 * </p>
 *
 * @author 孙峻
 * @since 2022-03-09
 */
@RestController
@RequestMapping("/praise")
@Api(tags = "点赞模块")
public class PraiseController {

    @Autowired
    private PraiseService praiseService;


    @PutMapping("/add")
    @ApiOperation("点赞接口")
    @AuthCheck
    @CacheEvict(cacheNames = {"article-detail", "comment-list", "fix-type", "article-list"}, allEntries = true, keyGenerator = RedisConst.REDIS_SJ_KEY_GENERATOR, condition = "#result.code == 200")
    public ApiResult addPraise(@RequestBody PraiseParam praiseParam) {
        User user = LocalUser.getUser();
        Praise praise = new Praise();
        BeanUtil.copyProperties(praiseParam, praise, "typeId");
        praise.setUserId(user.getId());
        if (Const.ARTICLE.equals(praiseParam.getGiveType())) {
            praise.setArticleId(praiseParam.getTypeId());
        } else if (Const.ANSWER.equals(praiseParam.getGiveType())) {
            praise.setAnswerId(praiseParam.getTypeId());
        } else if (Const.COMMENT.equals(praiseParam.getGiveType())) {
            praise.setCommentId(praiseParam.getTypeId());
        } else {
            throw new CustomException("文章类型有误");
        }
        // 首先判断该文章该对象是否点赞或者踩
        Boolean checkIsPraise = praiseService.checkUserIsPraise(user.getId(), praiseParam.getTypeId(), praiseParam.getGiveType(), praiseParam.getPraiseType());
        if (checkIsPraise) {
            return ApiResult.success("您已经点过赞了，请不要重复点赞哦~");
        }
        // 如果没有点赞
        boolean result = praiseService.save(praise);
        if (result) {
            return ApiResult.success("点赞成功");
        }
        return ApiResult.error("点赞失败");
    }

}
